% Display area activity as a movie given the spike history from the C simulation.
%  displayMovie({'areaname1' 'areaname2' ...}, areas_first_neuron_index[], 
%    areas_last_neuron_index[], areas_rows[], areas_cols[] , spike_data, 
%    relative_start_time, relative_end_time, file_end_msec, file_end_msec, 
%    smooth_msec, bin_msec, write_avi_movie)
%  
%  Here is a specific example:
%
% load sdat000170.dat
% displayMovieGeneric({'S' 'A'},[160 3232], [2207 5279], [32 32], [64 64],...
%      sdat000170,1,10000,160001,170000,1,5,false)
%
% where 
% 'S' and 'A' are labels for the areas in the plot
% Area 'S' starts at neuron index 160 and ends at 2207 (starting the count
% at 0); the assumption is that neurons are allocated consecutively for a 
% given area.  Area 'S' has 32 rows and 64 columns.  
% The file sdat00070.dat contains 2 columns: col1 = spike time in msec
% from the simulation start, and col2 = neuron number.
% The movie goes from the 1st msec, to the 10,000th msec.  
% sdat000170 recorded spikes starting at time 160000 through 169999.
% A time constant of 1 means no smoothing.  The bin size of 1 indicates
% binning of spikes in 5 msec bins; false means don't write a .avi movie 
% file.
%  
%  if smooth_msec ~=1, then it smooths with time constant = smooth_msec.
%  bin_msec bins 'bin_msec' milliseconds together
%
% 
function displayMovie(area_cell_array, first, last, rows, cols , sdat , start_time, end_time, ...
    file_start_msec, file_end_msec, smooth_msec, bin_msec, write_avi_movie)


persistent a

for i = 1:length(area_cell_array)
    first(i) = first(i) + 1;  % matlab arrays start at 1.
    last(i) = last(i) + 1;
	a(i).a=zeros(rows(i),cols(i));
end

num_neurons = max(last);
%filename = ['sdat' numTOstr( sdat_file_time, 6) '.dat' ]
%sdat = load(filename);
S=sparse(sdat(:,2)+1, sdat(:,1)+1-file_start_msec, 1, max(num_neurons,max(sdat(:,2))+1), (file_end_msec-file_start_msec+1));

%       set(gca,'xlim',[-80 80],'ylim',[-80 80],...
%       	   'NextPlot','replace','Visible','off')

fig=figure(1);
set(fig,'DoubleBuffer','on');

if write_avi_movie 
	mov = avifile('network.avi')
end

factor = 1000/bin_msec;
for i=start_time:bin_msec:end_time 

   for area = 1:length(area_cell_array)
	subplot( length(area_cell_array), 1, area);
	if smooth_msec > 1
		a(area).a=(smooth_msec-1)/smooth_msec*a(area).a + reshape( sum( S( first(area):last(area), i:(i+bin_msec-1)) ,2) , rows(area), cols(area) );
		%a(area).a=(smooth_msec-1)/smooth_msec*a(area).a + reshape( S( first(area):last(area), i) , rows(area), cols(area) );

		imagesc( factor*a(area).a ,[0 100]); colormap(gray);
	else
		imagesc( factor*full(reshape( sum( S( first(area):last(area), i:(i+bin_msec-1)) ,2) , rows(area), cols(area) )) ,[0 100]); colormap(gray);
	end
	
	title( area_cell_array{area} );


   end


   xlabel(num2str(i));
   drawnow;
   %pause(.5); 

   if write_avi_movie 
	F = getframe(gca);
   	mov = addframe(mov,F);
   end
end

if write_avi_movie
	mov = close(mov);
end
